package middleware

import (
	"context"
	"time"

	"mini-app/config/redis"
	"mini-app/internal/define"
	"mini-app/internal/pkg"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
)

// LoginCheck 登录校验
func LoginCheck() gin.HandlerFunc {
	return func(c *gin.Context) {
		debugSecret := c.GetHeader("debug-secret")
		debugOpenId := c.GetHeader("debug-open-id")
		if debugSecret == "secret-123-789" && debugOpenId != "" { // only for debug
			c.Set("token", "debug-token-xxx-567")
			c.Set("openid", debugOpenId)
			c.Set("session_key", "debug-session-key-xxx-234")
			c.Next()
			return
		}
		token := c.GetHeader("Authorization")
		if token == "" {
			response.JSON(c, nil, errorx.New("请重新登录", define.ErrTokenEmpty))
			c.Abort()
			return
		}
		rdb := redis.NewDB()
		// 获取会话参数
		timeoutCtx, cancel := context.WithTimeout(c.Request.Context(), time.Second*3)
		defer cancel()
		openid, _ := rdb.Get(timeoutCtx, define.MiniAppSessionOpenid+token).Result()
		sessionKey, _ := rdb.Get(timeoutCtx, define.MiniAppSessionKey+token).Result()
		if openid == "" || sessionKey == "" {
			response.JSON(c, nil, errorx.New("请重新登录", define.ErrTokenInvalid))
			c.Abort()
			return
		}
		// 验证登录
		err := pkg.MiniProgram{}.MiniCheckSession(c.Request.Context(), token)
		if err != nil {
			response.JSON(c, nil, err)
			c.Abort()
			return
		}
		c.Set("token", token)
		c.Set("openid", openid)
		c.Set("session_key", sessionKey)
		c.Next()
	}
}

func LoginCheckAd() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token == "" {
			response.JSON(c, nil, errorx.New("请重新登录", 100399))
			c.Abort()
			return
		}
		rdb := redis.NewDB()
		// 获取会话参数
		timeoutCtx, cancel := context.WithTimeout(c.Request.Context(), time.Second*3)
		defer cancel()
		openid, _ := rdb.Get(timeoutCtx, define.MiniAppSessionOpenid+token).Result()
		sessionKey, _ := rdb.Get(timeoutCtx, define.MiniAppSessionKey+token).Result()
		if openid == "" || sessionKey == "" {
			response.JSON(c, nil, errorx.New("请重新登录", 100499))
			c.Abort()
			return
		}
		// 验证登录
		err := pkg.MiniProgram{}.MiniCheckSessionAdvertisement(c.Request.Context(), token)
		if err != nil {
			response.JSON(c, nil, err)
			c.Abort()
			return
		}
		c.Set("token", token)
		c.Set("openid", openid)
		c.Set("session_key", sessionKey)
		c.Next()
	}
}
